import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/5 14:52
 * @description 双指针 + 滑动窗口，由于arr[i]都是正数，说明超过target只能移动左指针
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = {1,6,1};
        solution.minSumOfLengths(arr, 7);
    }
    public int minSumOfLengths(int[] arr, int target) {
        List<int[]> list = new ArrayList<>();
        int n = arr.length;
        int l = 0, r = 0;
        int sum = 0;
        while (r < n) {
            sum += arr[r];
            while (sum > target) {
                sum -= arr[l];
                l++;
            }
            if (sum == target) {
                list.add(new int[]{l, r, r - l + 1});
            }
            r++;
        }
        if (list.size() < 2) {
            return -1;
        }
        list.sort((a,b)-> a[2] - b[2]);
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < list.size(); i++) {
            int[] first = list.get(i);
            for (int j = i + 1; j < list.size(); j++) {
                if (first[0] > list.get(j)[1] || first[1] < list.get(j)[0]) {
                    ans = Math.min(ans, first[2] + list.get(j)[2]);
                }
            }
        }
        return ans == Integer.MAX_VALUE ? -1 : ans;
    }
}
